//
//  ZYComposeTextView.swift
//  weiboZY
//
//  Created by 赵勇 on 16/5/19.
//  Copyright © 2016年 赵勇. All rights reserved.
//

import UIKit


// 自定义textView
// 实时看到xib的效果
@IBDesignable
class ZYComposeTextView: UITextView {

    // 懒加载lable
    private lazy var placeholderLabel: UILabel = {
       
//        let label = UILabel(textColor: UIColor.darkGrayColor(), font: 15)
        let label = UILabel()
        label.textColor = UIColor.darkGrayColor()
        label.text = "请数据发布的微博信息！"
        label.numberOfLines = 0
        return label
    
    }()
    
    // 设置外部使用的占位文字
    // @IBInspectable 让属性在xib中显示
    @IBInspectable var placeHolderStr: String? {
        didSet{
            
            placeholderLabel.text = placeHolderStr
            
        }

    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        
        // 监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)

        
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        super.init(coder: aDecoder)
        setupUI()
        
        // 监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
  
    private func setupUI() {
        // 添加label
        addSubview(placeholderLabel)
        
        // 使用系统的约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
   
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 指定label 位置
        placeholderLabel.frame.origin.x = 5
        placeholderLabel.frame.origin.y = 8
        
        
    }

   override var font: UIFont? {
     
        didSet{
           
            if font == nil {
                return
            }
            placeholderLabel.font = font
            
        }
    
    }
    
    override var text: String? {
        didSet{
            
            placeholderLabel.hidden = hasText()
        }
        
    }
    
    // 通知实行的方法
   @objc private func textChange() {
        
        placeholderLabel.hidden = hasText()
        
    }
    
    
    // 移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}
